/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.vttu.thietbi;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import vn.edu.vttu.readxml.ReadXML;
import vn.edu.vttu.readxml.thongtindb;

/**
 *
 * @author nhphuoc
 */
public class QuanLy_ThietBi extends javax.swing.JFrame {

    /**
     * Creates new form QuanLy_ThietBi
     */
    private boolean them = false;

    public QuanLy_ThietBi() {
        initComponents();
        setLocation(420, 120);
        loadtb();
        enableButton(true);
        txtTenThietBi.setEnabled(false);
        txtXuatXu.setEnabled(false);
    }

    private void loadtb() {
        try {
            ReadXML read = new ReadXML();
            Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
            vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
            TableModel tb = common.LoadThietBi();
            tbThietBi.setModel(tb);
            this.tbThietBi.setRowSelectionInterval(0, 0);
            txtMa.setText(String.valueOf(tbThietBi.getValueAt(0, 0)));
            txtTenThietBi.setText(String.valueOf(tbThietBi.getValueAt(0, 1)));
            txtXuatXu.setText(String.valueOf(tbThietBi.getValueAt(0, 2)));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void enableButton(boolean b) {
        btnThem.setEnabled(b);
        btnSua.setEnabled(b);
        btnXoa.setEnabled(b);
        btnLuu.setEnabled(!b);

        tbThietBi.setEnabled(b);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtMa = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtTenThietBi = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtXuatXu = new javax.swing.JTextField();
        btnThem = new javax.swing.JButton();
        btnSua = new javax.swing.JButton();
        btnXoa = new javax.swing.JButton();
        btnLuu = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtTim = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbThietBi = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 0, 255));
        jLabel1.setText("QUẢN LÝ THIẾT BỊ");

        jLabel2.setText("Mã: ");

        jLabel3.setText("Tên Thiết Bị");

        jLabel4.setText("Xuất Xứ");

        btnThem.setText("Thêm");
        btnThem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemActionPerformed(evt);
            }
        });

        btnSua.setText("Sửa");
        btnSua.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSuaActionPerformed(evt);
            }
        });

        btnXoa.setText("Xóa");
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        btnLuu.setText("Lưu");
        btnLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuActionPerformed(evt);
            }
        });

        jButton5.setText("Reload");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton1.setText("Print");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Danh sách thiết bị"));

        txtTim.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTimKeyTyped(evt);
            }
        });

        tbThietBi.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbThietBiMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbThietBi);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(txtTim, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtTim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 16, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(126, 126, 126)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(139, 139, 139))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnThem)
                        .addGap(3, 3, 3)
                        .addComponent(btnSua))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtMa, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtTenThietBi, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtXuatXu))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnXoa)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLuu)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtMa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(txtTenThietBi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtXuatXu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnThem)
                    .addComponent(btnSua)
                    .addComponent(btnXoa)
                    .addComponent(btnLuu)
                    .addComponent(jButton5)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tbThietBiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbThietBiMouseClicked
        int index = tbThietBi.getSelectedRow();
        txtMa.setText(String.valueOf(tbThietBi.getValueAt(index, 0)));
        txtTenThietBi.setText(String.valueOf(tbThietBi.getValueAt(index, 1)));
        txtXuatXu.setText(String.valueOf(tbThietBi.getValueAt(index, 2)));
    }//GEN-LAST:event_tbThietBiMouseClicked

    private void btnThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemActionPerformed
        them = true;
        txtTenThietBi.setText("");
        txtXuatXu.setText("");
        txtTenThietBi.setEnabled(true);
        txtXuatXu.setEnabled(true);
        enableButton(false);
    }//GEN-LAST:event_btnThemActionPerformed

    private void btnSuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSuaActionPerformed
        them = false;
        txtTenThietBi.setEnabled(true);
        txtXuatXu.setEnabled(true);
        enableButton(false);
    }//GEN-LAST:event_btnSuaActionPerformed

    private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed

        int dongiadv;
        if (txtTenThietBi.getText().equals("") || txtXuatXu.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Bạn chưa nhập tên dịch vụ hoặc đơn giá");
            if (txtTenThietBi.getText().equals("")) {
                txtTenThietBi.requestFocus();
            } else {
                txtXuatXu.requestFocus();
            }
        } else {
            String tendichvu = txtTenThietBi.getText().trim();
            String xuatxu = txtXuatXu.getText().toString().trim();

            if (them == true) {
                try {                    
                    ReadXML read = new ReadXML();
                    Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
                    vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
                    boolean x = common.insertThietBi(tendichvu, xuatxu);
                    if (x) {
                        JOptionPane.showMessageDialog(rootPane, "Thêm thiết bị thành công");
                        loadtb();
                        enableButton(true);
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Thêm thiết bị không thành công");
                        loadtb();
                        enableButton(true);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Đã xay ra lỗi: " + ex.getMessage());
                    loadtb();
                    enableButton(true);
                    enableButton(true);
                }

            } else {
                try {
                    int id = Integer.parseInt(txtMa.getText().toString());
                    ReadXML read = new ReadXML();
                    Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
                    vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
                    boolean x = common.updateThietBi(id, tendichvu, xuatxu);
                    if (x) {
                        JOptionPane.showMessageDialog(rootPane, "Cập nhật thiết bị thành công");
                        loadtb();
                        enableButton(true);
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Cập nhật thiết bị không thành công");
                        loadtb();
                        enableButton(true);
                    }
                }catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Đã xay ra lỗi: " + ex.getMessage());
                    loadtb();
                    enableButton(true);
                    enableButton(true);
                }
                }
            }
    }//GEN-LAST:event_btnLuuActionPerformed

    private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
        if (txtXuatXu.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Chưa chọn thiết bị để xóa");
        } else {
            int i = JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa dữ liệu này không?", "Cảnh Báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (i == 0) {
                try {
                    int id = Integer.parseInt(txtMa.getText().toString());
                    ReadXML read = new ReadXML();
                    Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
                    vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
                    boolean x = common.DeleteThietBi(id);
                    if (x) {
                        JOptionPane.showMessageDialog(rootPane, "Xóa thiết bị thành công");
                        loadtb();
                        enableButton(true);
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Xóa thiết bị không thành công");
                        loadtb();
                        enableButton(true);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Đã xay ra lỗi: " + ex.getMessage());
                    loadtb();
                    enableButton(true);
                    enableButton(true);
                }
            }
        }
    }//GEN-LAST:event_btnXoaActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        loadtb();
        enableButton(true);
        txtTenThietBi.setEnabled(false);
        txtXuatXu.setEnabled(false);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void txtTimKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTimKeyTyped
        try {
            ReadXML read = new ReadXML();
            Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
            vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
            TableModel tb = common.TimThietBi(txtTim.getText().trim());
            tbThietBi.setModel(tb);            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_txtTimKeyTyped

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String link = "src\\vn\\edu\\vttu\\thietbi\\danhsachthietbi.jrxml";
        try {
            //Tạo kết nối đến Mysql
            Class.forName("com.mysql.jdbc.Driver");
            String database = "jdbc:mysql://"+thongtindb.getIp()+":"+thongtindb.getPort()+"/"+thongtindb.getDb();
            String us = thongtindb.getU();
            String pa = thongtindb.getP();
            Map<String, Object> params = new HashMap<String, Object>();  
            Connection conn = (Connection) DriverManager.getConnection(database, us, pa);
            // tạo JasperReport
            JasperReport jr = JasperCompileManager.compileReport(link);
            //tạo JasperPrint
            JasperPrint jp = JasperFillManager.fillReport(jr, params, conn);            
            JasperViewer jv = new JasperViewer(jp, false); 
            jv.setVisible(true); 
        } catch (Exception ex) {

        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
         * @param args the command line arguments
         */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QuanLy_ThietBi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QuanLy_ThietBi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QuanLy_ThietBi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QuanLy_ThietBi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuanLy_ThietBi().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLuu;
    private javax.swing.JButton btnSua;
    private javax.swing.JButton btnThem;
    private javax.swing.JButton btnXoa;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbThietBi;
    private javax.swing.JTextField txtMa;
    private javax.swing.JTextField txtTenThietBi;
    private javax.swing.JTextField txtTim;
    private javax.swing.JTextField txtXuatXu;
    // End of variables declaration//GEN-END:variables
}
